package core

import (
	"github.com/blang/semver/v4"
	"github.com/pkg/errors"
	"hpmGo/constants"
	"os"
	"path/filepath"
)

type LocalRepository struct {
}

func (localRepo LocalRepository) Manifest(name string, version string) (Manifest, error) {
	cwd, _ := os.Getwd()
	scope, name := ParseScopeName(name)
	bundleJsonPath := filepath.Join(cwd, constants.OHOS_BUNDLES, scope, name, "bundle.json")
	m, err := FromBundleJson(bundleJsonPath)
	v, _ := semver.Make(version)
	mv, _ := semver.Make(m.Version)
	if v.GT(mv) {
		return Manifest{}, errors.New("manifest need update")
	}
	return m, err
}

func (localRepo LocalRepository) Resolve(bundle Bundle) (manifests []Manifest, err error) {
	for name := range bundle.Dependencies {
		versionRange := bundle.Dependencies[name]
		m, err := localRepo.Manifest(name, versionRange)
		if err != nil {
			return nil, err
		}
		manifests = append(manifests, m)
	}
	return
}
